﻿using System;
using System.Collections.Generic;
using System.Composition;
using System.Diagnostics;
using System.Threading.Tasks;
using Unread.Business.Data.Opml.Interfaces;
using Unread.Business.Data.Storage.Interfaces;
using Unread.Business.Models;
using Unread.Business.Repositories.Interfaces;
using Unread.Business.Services.Interfaces;
using Windows.Storage;
using Windows.Storage.Pickers;

namespace Unread.Business.Services
{
    [Export(typeof(IFeedsImporter))]
    internal class FeedsImporter : IFeedsImporter
    {
        private readonly List<string> _fileTypes = new List<string> { ".xml", ".opml" };

        private readonly IFileReadPicker _fileOpenPicker;
        private readonly IOpmlReader _opmlReader;
        private readonly IFeedRepository _feedRepository;

        [ImportingConstructor]
        public FeedsImporter(IFileReadPicker fileOpenPicker, IOpmlReader opmlReader, IFeedRepository feedRepository)
        {
            if (fileOpenPicker == null) throw new ArgumentNullException("fileOpenPicker");
            if (opmlReader == null) throw new ArgumentNullException("opmlReader");
            if (feedRepository == null) throw new ArgumentNullException("feedRepository");

            _fileOpenPicker = fileOpenPicker;
            _opmlReader = opmlReader;
            _feedRepository = feedRepository;
        }

        public async Task Import()
        {
            var file = await _fileOpenPicker.PickSingleFileAsync(PickerViewMode.List, PickerLocationId.DocumentsLibrary, _fileTypes);
            if (file == null)
            {
                Debug.WriteLine("No feeds imported, no file selected");
                return;
            }

            var feeds = await MapFileToFeeds(file);

            await SaveFeeds(feeds);
        }

        private async Task<List<Feed>> MapFileToFeeds(StorageFile file)
        {
            var fileContents = await FileIO.ReadTextAsync(file);
            var opml = _opmlReader.Read(fileContents);
            var feeds = Feed.MapOutlinesToFeeds(opml.Body.Outlines);

            return feeds;
        }

        private async Task SaveFeeds(List<Feed> feeds)
        {
            foreach (var feed in feeds)
            {
                await _feedRepository.Create(feed);
            }
        }
    }
}